<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场地名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入场地名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['site:site:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['site:site:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['site:site:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['site:site:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="siteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="场地名称" align="center" prop="name" />
      <el-table-column label="场地地址" align="center" prop="address" />
      <el-table-column label="主要联系人" align="center" prop="contacts" />
      <el-table-column label="联系人电话" align="center" prop="mobile" />
      <el-table-column label="所属区域" align="center" prop="deptName" />
      <el-table-column label="纬度" align="center" prop="latitude" width="100" />
      <el-table-column label="经度" align="center" prop="longitude" width="100" />
      <el-table-column label="状态" align="center" prop="state" width="80" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['site:site:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['site:site:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改场地管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="场地名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入场地名称" />
        </el-form-item>
        <el-form-item label="场地地址" prop="address">
          <el-input readonly v-model="form.address" placeholder="请选择地址">
            <el-button slot="append" @click="POISearchDialog">选择经纬度</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="主要联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入主要联系人" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属区域" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择所属区域" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改设备信息对话框 -->
      <el-dialog width="600px" center title="选择经纬度" :visible.sync="innerVisible" :close-on-click-modal="false"
        append-to-body>
        <div>
          <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
            <!-- <el-input id="tipInput" v-model="poiKeywords" placeholder="请输入搜索名称"> -->
            <div>通过点击地图选择经纬度</div>
            <el-autocomplete class="inline-input" size="small" v-model="poiKeywords" :fetch-suggestions="querySearch"
              placeholder="请输入搜索名称" @select="handleSelect"></el-autocomplete>
          </div>
          <!-- <el-button slot="append" icon="el-icon-search" @click="searchKeyword" style="width:60px"></el-button> -->
          <!-- </el-input> -->
          <div ref="mapContainer" style="height:400px"></div>
          <div slot="footer" class="dialog-footer" align="right" style="margin-top:15px">
            <el-button type="primary" @click="confirmSelectAdress(1)">确 定</el-button>
            <el-button @click="confirmSelectAdress(0)">取 消</el-button>
          </div>
        </div>
      </el-dialog>
  </div>
</template>

<script>
const mapConfig = {
  securityJsCode: "b23c850a95afb3ca622bedf6efa527df",
  MAPKEY: "9b855993ebffd74a39d44888fff209f7",
};
import { listSite, getSite, delSite, addSite, updateSite } from "@/api/site/site";
import AMapLoader from "@amap/amap-jsapi-loader";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Site",
  dicts: ['common_status'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      deptOptions:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      innerVisible:false,
      // 总条数
      total: 0,
      // 场地管理表格数据
      siteList: [],
      // 弹出层标题
      title: "",
      poiKeywords: '',
      placeSearch: null,
      autoComplete: null,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "场地名称不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "场地地址不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属机构数id不能为空", trigger: "blur" }
        ],
        delFlag: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect() ;
  },
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询场地管理列表 */
    getList() {
      this.loading = true;
      listSite(this.queryParams).then(response => {
        this.siteList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        address: null,
        state: 1,
        deptId: null,
        ancestors: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加场地管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSite(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改场地管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSite(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSite(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除场地管理编号为"' + ids + '"的数据项？').then(function() {
        return delSite(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('site/site/export', {
        ...this.queryParams
      }, `site_${new Date().getTime()}.xlsx`)
    },
    querySearch(queryString, cb) {
      this.autoComplete.search(queryString, (status, result) => {
        var tips = result.tips || [];
        tips = tips.map(it => {
          it.value = it.name
          return it
        })
        // 调用 callback 返回建议列表的数据
        cb(tips);
      })
    },
    handleSelect(item) {
      this.placeSearch.setCity(item.adcode);
      this.placeSearch.search(item.name);
    },
    confirmSelectAdress(type) {
      // 确定
      if (type === 1) {
        if (this.currentSelectAddress) {
          const result = this.currentSelectAddress
          const { formattedAddress, addressComponent } = result
          const { location, province, city, district } = addressComponent
          this.form.longitude = location.lng
          this.form.latitude = location.lat
          this.form.address = formattedAddress

          // this.form.provinceCode = province
          // this.form.cityCode = city
          // this.form.adCode = district
        }
      }
      this.innerVisible = false
    },
    toEvent(row,type){
      this.$router.push({
        path: '/sysDevice/deviceEvent',
        query: { siteId: row.id , type:type }
      })
    },
    POISearchDialog() {
      this.innerVisible = true
      this.currentSelectAddress = null
      this.poiKeywords = ''
      this.$nextTick(async () => {
        const AMap = await AMapLoader.load({
          key: mapConfig.MAPKEY, // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.Geolocation"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        });

        this.map = new AMap.Map(this.$refs.mapContainer, {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          zoom: 12, //初始化地图级别
          // center: [116.405467, 39.907761], //初始化地图中心点位置
        });
        AMap.plugin(['AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geolocation'], () => {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量
            offset: [10, 20],
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            position: 'RB'
          })

          function onComplete(res) {
            const pointer = [res.position.lng, res.position.lat]
            // data是具体的定位信息
            this.map.setCenter(pointer);
          }

          function onError(res) {
            // 定位出错
            console.error(res.message)
          }
          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          });
          var autoOptions = {
            //city 限定城市，默认全国
            city: '广州',
            input: "tipinput"
          };
          // 实例化AutoComplete
          const geocoder = new AMap.Geocoder()
          this.autoComplete = new AMap.AutoComplete(autoOptions);
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 10, // 单页显示结果条数
            pageIndex: 1, // 页码
            map: this.map, // 展现结果的地图实例
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          });
          this.placeSearch.on('markerClick', (e) => {
            const { location } = e.data
            geocoder.getAddress(location, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const { addressComponent } = result.regeocode
                addressComponent.location = location
                this.currentSelectAddress = result.regeocode
              }
            })
          })
          // 监听鼠标点击地图点，生成marker
          this.map.on('click', (ev) => {
            if (this.currentMarker) {
              this.map.remove(this.currentMarker);
            }
            const { lng, lat } = ev.lnglat
            var marker = new AMap.Marker({
              icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
              position: [lng, lat],
              offset: new AMap.Pixel(-10, -27),
            });
            this.currentMarker = marker
            this.map.add(marker);
            geocoder.getAddress(ev.lnglat, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const { addressComponent } = result.regeocode
                addressComponent.location = ev.lnglat
                this.currentSelectAddress = result.regeocode
              }
            })
          });
        })
      })

    },
  }
};
</script>
